// SECURITY: This BFF proxy intentionally has no application-level rate limiting. // Rate limiting is the deployer's responsibility — configure it at the platform // edge (Vercel Firewall, Cloudflare, nginx) or add a Redis-backed limiter // (e.g. @upstash/ratelimit) here before going to production. Auth endpoints // like customers/login and customers/register are the most important to cover. import { NextRequest, NextResponse } from 'next/server'; import { cookies } from 'next/headers'; import { checkCsrf } from '@/core/lib/csrf'; import { buildAllowedBackendUrl } from '@/core/lib/bff-allowlist'; import { getRequestOrigin } from '@/core/lib/site-url'; import { SALES_CHANNEL_ID } from '@/core/lib/brainerce'; import { LEGACY_TOKEN_COOKIE, LOGGED_IN_COOKIE, expireCookie, isSecureCookie, tokenCookieName, } from '@/core/lib/auth-cookie'; import { bffBrowserMaxAgeSeconds, bffCacheKey, bffCacheRule, readThroughBff, type BffReply, } from '@/core/lib/bff-read-cache'; const BACKEND_URL = (process.env.BRAINERCE_API_URL || 'https://api.brainerce.com').replace( /\/$/, '' ); const TOKEN_COOKIE = tokenCookieName(); const COOKIE_MAX_AGE = 7 * 24 * 60 * 60; // 7 days const BACKEND_TIMEOUT_MS = 15_000; /** Auth endpoints whose responses contain tokens to intercept */ const AUTH_ENDPOINTS = ['customers/login', 'customers/register', 'customers/verify-email']; function isAuthEndpoint(path: string): boolean { return AUTH_ENDPOINTS.some((ep) => path.endsWith(ep)); } function isSafePathSegment(segment: string): boolean { if (!segment) return false; if (segment === '.' || segment === '..') return false; if (segment.includes('/') || segment.includes('\\')) return false; if (segment.includes('\0')) return false; return true; } function isSecure(): boolean { return isSecureCookie(); } /** * Reads a fetch `Response` body as text, self-healing an observed runtime bug: * on Next.js 15.5.26, a `fetch()` made from a Route Handler or Server * Component can return a Response whose body is still gzip-compressed bytes, * even though an identical request (same URL, same headers) made via plain * Node `fetch()` outside Next decompresses correctly — confirmed by diffing * the raw response bytes both ways. The exact point inside Next's * server-side fetch instrumentation that causes this isn't confirmed, only * the externally observable symptom is. Calling `.text()` on a Response like * that UTF-8-decodes still-gzipped bytes — lossy (replacement characters) * and unparseable as JSON. * * A correctly-behaving fetch (browsers; plain Node; this bug's absence) never * hands back bytes that still start with gzip's magic number (`1f 8b`) — real * compression has already been undone by the time a body reaches here — so * checking for it before ever decoding as text can't misfire into * double-decompressing an already-plain body. * * This only works because the backend request below pins `Accept-Encoding: * gzip` instead of the runtime default (which also offers Brotli) — Brotli * has no reliable magic-number signature and no Web Streams API decoder, so * this self-healing has no fallback for it. That header is * correctness-critical here, not a tuning choice: reverting it to the * runtime default reintroduces this exact corruption, just for * Brotli-compressed responses instead of gzip ones. */ async function readBackendBody(response: Response): Promise { const buffer = new Uint8Array(await response.arrayBuffer()); if (buffer.length >= 2 && buffer[0] === 0x1f && buffer[1] === 0x8b) { const decompressed = new Blob([buffer]).stream().pipeThrough(new DecompressionStream('gzip')); return new TextDecoder('utf-8').decode(await new Response(decompressed).arrayBuffer()); } return new TextDecoder('utf-8').decode(buffer); } type BackendResult = { response: Response } | { failure: NextResponse }; /** One call to the backend with the proxy's timeout; a transport failure is a 502/504, never a throw. */ async function callBackend( method: string, url: string, headers: Record, body: ArrayBuffer | string | undefined ): Promise { const abortController = new AbortController(); const timeoutId = setTimeout(() => abortController.abort(), BACKEND_TIMEOUT_MS); try { return { response: await fetch(url, { method, headers, body, signal: abortController.signal }), }; } catch (error) { const isTimeout = (error as Error)?.name === 'AbortError'; return { failure: NextResponse.json( { error: isTimeout ? 'Backend request timed out' : 'Backend service unavailable' }, { status: isTimeout ? 504 : 502 } ), }; } finally { clearTimeout(timeoutId); } } /** The headers a 429 needs to carry so the SDK in the browser can honour the API's `Retry-After`. */ function rateLimitHeaders(retryAfter: string | null | undefined): Record { return retryAfter ? { 'Retry-After': retryAfter } : {}; } /** * The reply a visitor gets for an anonymous public read, exactly as it will be shared: a failure to * reach the API is a 502/504, and a 5xx body is replaced so backend internals never leak. */ async function loadPublicReply( url: string, headers: Record, pathSegments: string ): Promise { const result = await callBackend('GET', url, headers, undefined); if ('failure' in result) { return { status: result.failure.status, body: await result.failure.text(), contentType: 'application/json', }; } const { response } = result; const text = await readBackendBody(response); if (response.status >= 500) { console.error(`[proxy] backend ${response.status} on ${pathSegments}:`, text); return { status: response.status, body: JSON.stringify({ error: 'Backend service error' }), contentType: 'application/json', }; } return { status: response.status, body: text, contentType: response.headers.get('Content-Type') || 'application/json', ...(response.status === 429 && response.headers.get('Retry-After') ? { retryAfter: response.headers.get('Retry-After') as string } : {}), }; } function setAuthCookies(response: NextResponse, token: string): void { // A session from before the `__Host-` prefix must not survive next to the new one. if (TOKEN_COOKIE !== LEGACY_TOKEN_COOKIE) expireCookie(response.cookies, LEGACY_TOKEN_COOKIE); response.cookies.set(TOKEN_COOKIE, token, { httpOnly: true, secure: isSecure(), sameSite: 'lax', path: '/', maxAge: COOKIE_MAX_AGE, }); // NOT a secret, and deliberately readable by the browser (httpOnly: false): the constant "1", a // "someone is logged in" hint so the storefront can render the signed-in UI (account link, wishlist // source) before /api/auth/me answers. It carries no token and grants nothing; the real // credential is the httpOnly cookie above, and the server never trusts this one. response.cookies.set(LOGGED_IN_COOKIE, '1', { httpOnly: false, secure: isSecure(), sameSite: 'lax', path: '/', maxAge: COOKIE_MAX_AGE, }); } function clearAuthCookies(response: NextResponse): void { expireCookie(response.cookies, TOKEN_COOKIE); expireCookie(response.cookies, LEGACY_TOKEN_COOKIE); response.cookies.delete(LOGGED_IN_COOKIE); } async function proxyRequest( request: NextRequest, params: { path: string[] } ): Promise { const method = request.method; // Reject path-traversal attempts before constructing the backend URL if (!params.path.every(isSafePathSegment)) { return NextResponse.json({ error: 'Invalid path' }, { status: 400 }); } // CSRF protection for mutating requests if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) { const csrfError = checkCsrf(request); if (csrfError) return csrfError; } // Build backend URL from path segments, and forward ONLY what this storefront's SDK calls (see // `bff-allowlist.ts`). This proxy attaches the shopper's token to what it forwards, so it must not be // a general passthrough: another path or another channel's `vc_*` answers 404 here, without a backend // call. The helper also refuses a segment that would resolve to a different path once the URL is // parsed (`..`, `%2e%2e`, an encoded slash, `?`, `#`, `;`) and re-checks the URL it built. const backendUrl = buildAllowedBackendUrl(BACKEND_URL, params.path, SALES_CHANNEL_ID); if (!backendUrl) { return NextResponse.json({ error: 'Not found' }, { status: 404 }); } const pathSegments = params.path.join('/'); // Forward query parameters request.nextUrl.searchParams.forEach((value, key) => { backendUrl.searchParams.set(key, value); }); // Build headers for backend request. Preserve the incoming Content-Type // (including the multipart boundary for file uploads); default to JSON // when absent. Overriding the Content-Type would strip the boundary and // corrupt multipart uploads on the backend. const incomingContentType = request.headers.get('content-type'); const headers: Record = { 'Content-Type': incomingContentType || 'application/json', // Pinned to gzip (not the runtime default `gzip, deflate, br`) so // readBackendBody()'s self-healing only has to reason about one wire // format — see the comment there. 'Accept-Encoding': 'gzip', }; // Send the proxy's own origin, never the client-supplied Origin header — // forwarding a client-controlled value would just hand a caller the ability // to pick which storefront the backend thinks it is talking to. // // ⛔ The backend READS this value: a LIVE sales channel accepts only the // domain configured on the connection (exact host or a subdomain of it) plus // any additional allowed origins. It is not a presence check. So this header // has to carry the storefront's PUBLIC origin. // // `request.nextUrl.origin` alone is not that origin: behind a reverse proxy // it can be an internal address (`http://localhost:3000`, a container host), // and every storefront call then fails on a Live connection. A TEST // connection with no domain configured accepts anything, which is why this // used to surface only at go-live. `getRequestOrigin` prefers the forwarded // host the browser actually used and falls back to configuration. headers['Origin'] = await getRequestOrigin(request.headers); // Forward SDK version header if present const sdkVersion = request.headers.get('x-sdk-version'); if (sdkVersion) { headers['X-SDK-Version'] = sdkVersion; } // Forward what this storefront says it can show (the SDK sends it when `features` is set). Without // it the backend never offers a shipping rate that needs the pickup point screen. const clientFeatures = request.headers.get('x-brainerce-features'); if (clientFeatures) { headers['X-Brainerce-Features'] = clientFeatures; } // Forward Accept-Language so the backend locale middleware can resolve translations const acceptLanguage = request.headers.get('accept-language'); if (acceptLanguage) { headers['Accept-Language'] = acceptLanguage; } // Add auth token from httpOnly cookie const cookieStore = await cookies(); const tokenCookie = cookieStore.get(TOKEN_COOKIE); if (tokenCookie?.value) { headers['Authorization'] = `Bearer ${tokenCookie.value}`; } // Forward request body for non-GET requests. Use ArrayBuffer so multipart // bodies (file uploads) pass through unchanged — `request.text()` works for // JSON but would break binary content. const isMultipart = incomingContentType?.includes('multipart/form-data') ?? false; let body: ArrayBuffer | string | undefined; if (method !== 'GET' && method !== 'HEAD') { try { body = isMultipart ? await request.arrayBuffer() : await request.text(); } catch { // No body } } // Anonymous reads of public, static content (header, footer, regions, capabilities, ...) are the // same for every visitor and arrive from one shared IP, so they are answered from a short cache // (see `bff-read-cache.ts` for exactly what it does and never does). A request that carries the // customer token is never cached. const cacheRule = bffCacheRule(method, pathSegments, SALES_CHANNEL_ID, !!tokenCookie?.value); const cacheKey = cacheRule ? bffCacheKey(pathSegments, request.nextUrl.searchParams, headers) : null; if (cacheRule && cacheKey) { const reply = await readThroughBff(cacheKey, cacheRule, () => loadPublicReply(backendUrl.toString(), headers, pathSegments) ); const cacheable = reply.status >= 200 && reply.status < 300; return new NextResponse(reply.body, { status: reply.status, headers: { 'Content-Type': reply.contentType, ...rateLimitHeaders(reply.retryAfter), // The browser may keep it too, so a tab asks this server once a minute, not once per page. // `private`: a shared cache in front of the store must not key it by address alone. ...(cacheable ? { 'Cache-Control': `private, max-age=${bffBrowserMaxAgeSeconds(cacheRule)}, stale-while-revalidate=300`, Vary: 'Accept-Language, X-Brainerce-Features', } : {}), }, }); } // Proxy the request to backend const backend = await callBackend(method, backendUrl.toString(), headers, body); if ('failure' in backend) return backend.failure; const backendResponse = backend.response; // Read response body const responseText = await readBackendBody(backendResponse); // For auth endpoints: intercept token, set cookie, strip token from response if (backendResponse.ok && method === 'POST' && isAuthEndpoint(pathSegments)) { try { const data = JSON.parse(responseText); if (data.token) { const token = data.token; // Strip token from client response const { token: _stripped, ...safeData } = data; const response = NextResponse.json(safeData, { status: backendResponse.status, }); setAuthCookies(response, token); return response; } } catch { // Not JSON or no token field — pass through } } // Handle 401 responses: clear auth cookies if (backendResponse.status === 401 && tokenCookie?.value) { const response = new NextResponse(responseText, { status: backendResponse.status, headers: { 'Content-Type': backendResponse.headers.get('Content-Type') || 'application/json', }, }); clearAuthCookies(response); return response; } // Sanitize 5xx responses so backend internals don't leak to the client if (backendResponse.status >= 500) { console.error(`[proxy] backend ${backendResponse.status} on ${pathSegments}:`, responseText); return NextResponse.json( { error: 'Backend service error' }, { status: backendResponse.status } ); } // Pass through response as-is. A 429 keeps its `Retry-After`: the SDK waits that long and retries // once, but only if the header reaches it, and this proxy used to drop it. return new NextResponse(responseText, { status: backendResponse.status, headers: { 'Content-Type': backendResponse.headers.get('Content-Type') || 'application/json', ...(backendResponse.status === 429 ? rateLimitHeaders(backendResponse.headers.get('Retry-After')) : {}), }, }); } export async function GET( request: NextRequest, { params }: { params: Promise<{ path: string[] }> } ) { return proxyRequest(request, await params); } export async function POST( request: NextRequest, { params }: { params: Promise<{ path: string[] }> } ) { return proxyRequest(request, await params); } export async function PUT( request: NextRequest, { params }: { params: Promise<{ path: string[] }> } ) { return proxyRequest(request, await params); } export async function PATCH( request: NextRequest, { params }: { params: Promise<{ path: string[] }> } ) { return proxyRequest(request, await params); } export async function DELETE( request: NextRequest, { params }: { params: Promise<{ path: string[] }> } ) { return proxyRequest(request, await params); }